package com.duan.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duan.cart.feign.CartFeign;
import com.duan.cart.pojo.Cart;
import com.duan.config.TokenDecode;
import com.duan.entity.StatusCode;
import com.duan.goods.feign.ProductFeign;
import com.duan.goods.pojo.ProductDetails;
import com.duan.order.config.RabbitMqConfig;
import com.duan.order.pojo.Order;
import com.duan.order.pojo.Task;
import com.duan.order.service.OrderService;
import com.duan.order.mapper.OrderMapper;
import com.duan.order.service.TaskService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.soap.Addressing;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author lenovo
 * @description 针对表【duan_order】的数据库操作Service实现
 * @createDate 2024-08-08 17:07:39
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private TaskService taskService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private ProductFeign productFeign;

    @Override
    public List<Order> selectAll() {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getIsDelete, 0);
        return orderMapper.selectList(queryWrapper);
    }

    @Override
    public List<Order> selectList(Order order) {
        LambdaQueryWrapper<Order> queryWrapper = this.queryWrapper(order);
        return orderMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public Integer insert(Order order) {
        //减库存失败，判断是否是库存不足
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(order.getProductId());
        productDetails.setIsDelete(0);
        List<ProductDetails> list = productFeign.select(productDetails).getData();
        if(list.get(0).getInventory()<order.getNum()){
            return -2;
        }
        //新增订单
        String userName = tokenDecode.getUserInfo().get("user_name");
        order.setBuyerName(userName);
        order.setId(IdWorker.getId());
        int insert = orderMapper.insert(order);
        if(insert != 1){
            return -3;
        }
        //把要发送的消息存到task表中
        Task task = new Task();
        task.setId(IdWorker.getId());
        task.setTaskType("0");
        task.setMqExchange(RabbitMqConfig.ORDER_EXCHANGE);
        task.setMqRoutingkey(RabbitMqConfig.ORDER_QUEUE);
        task.setRequestBody(JSON.toJSONString(order));
        taskService.insert(task);
        //发送消息
        rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE,RabbitMqConfig.ORDER_QUEUE, JSON.toJSONString(task));
        //清楚购物车
//        rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE,RabbitMqConfig.CART_QUEUE,JSON.toJSONString(order));
        cartFeign.delete(String.valueOf(order.getProductId()));
        return 1;
    }

    @Override
    @Transactional
    public Integer delete(String ids) {
        try {
            String[] split = ids.split(",");
            for (String id : split) {
                Order order = new Order();
                order.setId(Long.parseLong(id));
                order.setIsDelete(1);
                orderMapper.updateById(order);
            }
            return 1;
        } catch (Exception e) {
            return -1;
        }

    }

    @Override
    public Integer update(Order order) {
        return orderMapper.updateById(order);
    }

    @Override
    public Page<Order> pageAll(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return (Page<Order>) this.selectAll();
    }

    @Override
    public Page<Order> pageList(Order order, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return (Page<Order>) this.selectList(order);
    }

    @Override
    public Integer cartInsert(Map map) {
        List list = JSONObject.parseObject(JSONObject.toJSONString(map.get("cart")), List.class);
        Object address_id = map.get("address_id");
        for (Object o : list) {
            Cart cart = JSONObject.parseObject(JSONObject.toJSONString(o), Cart.class);
            Order order=new Order();
            order.setProductId(cart.getProductId());
            order.setNum(cart.getNum());
            order.setMoney(cart.getMoney());
            order.setAddressId(Long.valueOf(address_id.toString()));
            order.setSource(0);
            order.setType(0);
            this.insert(order);
        }
        return 1;
    }

    @Override
    public Integer clearCart(Map map) {
        List<Cart> data = cartFeign.selectCart().getData();
        map.put("cart",data);
        this.cartInsert(map);
        return 1;
    }

    public LambdaQueryWrapper<Order> queryWrapper(Order order) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        if (order.getId() != null) {
            queryWrapper.eq(Order::getId, order.getId());
        }
        if (order.getSource() != null) {
            queryWrapper.eq(Order::getSource, order.getSource());
        }
        if (order.getType() != null) {
            queryWrapper.eq(Order::getType, order.getType());
        }
        if (order.getBuyerName() != null) {
            queryWrapper.eq(Order::getBuyerName, order.getBuyerName());
        }
        if (order.getMoney() != null) {
            queryWrapper.eq(Order::getMoney, order.getMoney());
        }
        if (order.getStatus() != null) {
            queryWrapper.eq(Order::getStatus, order.getStatus());
        }
        if (order.getUpdateTime() != null) {
            queryWrapper.eq(Order::getUpdateTime, order.getUpdateTime());
        }
        if (order.getCreateTime() != null) {
            queryWrapper.eq(Order::getCreateTime, order.getCreateTime());
        }
        if (order.getIsDelete() != null) {
            queryWrapper.eq(Order::getIsDelete, order.getIsDelete());
        }
        if (order.getAddressId() != null) {
            queryWrapper.eq(Order::getAddressId, order.getAddressId());
        }
        if (order.getProductId() != null) {
            queryWrapper.eq(Order::getProductId, order.getProductId());
        }
        if (order.getNum() != null) {
            queryWrapper.eq(Order::getNum, order.getNum());
        }
        if (order.getTradeNo() != null) {
            queryWrapper.eq(Order::getTradeNo, order.getTradeNo());
        }
        return queryWrapper;
    }

}




